from flask import render_template, g, request, jsonify, current_app, session

from info import db, constants
from info.models import Category, News
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blue


@profile_blue.route('/news_list')
@user_login_data
def news_list():
	# 获取参数
	page = request.args.get('p', 1)

	# 校验参数
	try:
		page = int(page)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

	# 数据库查询
	user = g.user
	news_model_list = []
	current_page = []
	total_page = []
	try:
		paginates = News.query.filter(News.user_id == user.id).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT,
		                                                                False)
		# 获取分页数据
		news_model_list = paginates.items
		# 获取当前页
		current_page = paginates.page
		# 获取总页数
		total_page = paginates.pages

	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

	news_dict_li = []
	for news in news_model_list:
		news_dict_li.append(news.to_review_dict())

	data = {
		'news_list': news_dict_li,
		'total_page': total_page,
		'current_page': current_page
	}

	return render_template('news/user_news_list.html', data=data)


@profile_blue.route('/user_news_release', methods=['GET', 'POST'])
@user_login_data
def user_news_release():
	if request.method == 'GET':
		try:
			categories = Category.query.all()
		except Exception as e:
			current_app.logger.error(e)
			return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

		category_dict_li = []
		for category in categories:
			category_dict_li.append(category.to_dict())
		category_dict_li.pop(0)

		data = {
			'categories': category_dict_li
		}

		return render_template('news/user_news_release.html', data=data)

	# POST 发布
	title = request.form.get("title")
	source = "个人发布"
	# 摘要
	digest = request.form.get("digest")
	content = request.form.get("content")
	index_image = request.files.get("index_image")
	category_id = request.form.get("category_id")

	# 校验参数
	if not all([title, source, digest, content, index_image, category_id]):
		return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

	try:
		category_id = int(category_id)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

	try:
		category = Category.query.get(category_id)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")

	if not category:
		return jsonify(errno=RET.NODATA, errmsg="没有此分类")

	# 添加图片
	try:
		index_image_data = index_image.read()
		image_file_name = storage(index_image_data)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

	# 添加到数据库
	news = News()
	news.title = title
	news.digest = digest
	news.source = source
	news.content = content
	news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_file_name
	news.category_id = category_id
	news.user_id = g.user.id
	# 1代表待审核状态
	news.status = 1

	# 4. 保存到数据库
	try:
		db.session.add(news)
		db.session.commit()
	except Exception as e:
		db.session.rollback()
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
	# 5. 返回结果
	return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


"""
个人中心 - 我的收藏
URL: /user/collection
请求方式：GET
"""


@profile_blue.route('/collection')
@user_login_data
def user_collection():
	# 获取页数
	page = request.args.get("page", 1)
	try:
		page = int(page)
	except Exception as e:
		current_app.logger.error(e)
		page = 1

	user = g.user

	collections = []
	current_page = 1
	total_page = 1
	try:
		# 进行分页数据查询
		paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
		# 获取分页数据
		collections = paginate.items
		# 获取当前页
		current_page = paginate.page
		# 获取总页数
		total_page = paginate.pages
	except Exception as e:
		current_app.logger.error(e)

	# 收藏列表
	collection_dict_li = []
	for news in collections:
		collection_dict_li.append(news.to_basic_dict())

	data = {"total_page": total_page, "current_page": current_page, "collections": collection_dict_li}

	return render_template('news/user_collection.html', data=data)


"""
个人中心 - 修改密码
URL: /user/base_info
请求方式：GET & POST
"""


@profile_blue.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
	if request.method == 'GET':
		return render_template('news/user_pass_info.html')

	# 密码修改
	old_password = request.json.get('old_password')
	new_password = request.json.get('new_password')

	if not all([old_password, new_password]):
		return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

	# 逻辑处理部分
	user = g.user
	if not user.check_passowrd(old_password):
		return jsonify(errno=RET.PWDERR, errmsg='原密码错误')

	user.password = new_password

	return jsonify(errno=RET.OK, errmsg='密码修改成功')


"""
个人中心 - 头像设置
URL: /user/base_info
请求方式：GET & POST
"""


@profile_blue.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
	user = g.user
	if request.method == 'GET':
		return render_template('news/user_pic_info.html', data={"user": user.to_dict()})

	# 上传头像
	# 获取文件
	try:
		avatar = request.files.get('avatar').read()
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.PARAMERR, errmsg='读取文件错误')

	# 上传到七牛云
	try:
		key = storage(avatar)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(errno=RET.THIRDERR, errmsg='上传图像失败')

	# 添加到数据库
	user.avatar_url = key

	data = {
		'avatar_url': constants.QINIU_DOMIN_PREFIX + key
	}

	return jsonify(errno=RET.OK, errmsg='上传成功', data=data)


"""
个人中心 - 基础资料
URL: /user/base_info
请求方式：GET & POST
"""


@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
	if request.method == 'GET':
		user = g.user
		data = {
			'user': user.to_dict() if user else None
		}
		return render_template('news/user_base_info.html', data=data)

	# 1.获取参数
	params_dict = request.json
	signature = params_dict.get('signature')
	nick_name = params_dict.get('nick_name')
	gender = params_dict.get('gender')

	# 2.校验参数
	if not all([nick_name, signature, gender]):
		return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

	if gender not in ['MAN', 'WOMAN']:
		return jsonify(errno=RET.PARAMERR, errmsg='性别错误')

	# 3.修改信息并上传
	user = g.user

	user.nick_name = nick_name
	user.signature = signature
	user.gender = gender

	try:
		db.session.commit()
	except Exception as e:
		db.session.rollback()
		current_app.logger.error(e)
		return jsonify(errno=RET.DBERR, errmsg='用户信息修改失败')

	session['nick_name'] = nick_name

	return jsonify(errno=RET.OK, errmsg='保存成功')


"""
个人中心首页
URL:/user/info
"""


@profile_blue.route('/info')
@user_login_data
def user_info():
	user = g.user

	data = {
		'user': user.to_dict() if user else None
	}

	return render_template('news/user.html', data=data)
